package com.wangweixiong.role.controller;

import com.alibaba.fastjson.JSONObject;
import com.wangweixiong.role.base.BaseController;
import com.wangweixiong.role.bean.RoleBean;
import com.wangweixiong.role.service.RoleService;
import com.wangweixiong.role.service.impl.RoleServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet(name="RoleControllerPostWWX",urlPatterns="/wwx/post")

public class RoleControllerPostWWX extends BaseController {
    private RoleService roleService =new RoleServiceImpl();
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        // 解决乱码问题
        servletRequest.setCharacterEncoding("UTF-8");
        // 从请求拿数据
        BufferedReader reader = servletRequest.getReader();
        String ss = reader.readLine();
        JSONObject jsonobject = JSONObject.parseObject(ss);
        String method=jsonobject.getString("method");
        String rs=jsonobject.getString("id");
        String name=jsonobject.getString("name");
        Object ids = jsonobject.get("ids");
        // 根据method的不同进入不同方法
        if(method.equals("add")){
            add(name, servletResponse);
        }else if(method.equals("delete")){
            delete(ids, servletResponse);
        }else if(method.equals("update")){
            update(rs,name,servletResponse);


        }
    }

    private void update(String rs,String name, ServletResponse servletResponse) throws IOException {

        Integer id = Integer.parseInt(rs);
        Integer integer = roleService.updateRole(id,name);
        printData(integer>0,null,500, servletResponse);
    }

    private void delete(Object ids, ServletResponse servletResponse) throws IOException {


        List<Integer> userIds = roleService.deleteRoleById(ids);
        printData(userIds.size()==0,userIds,500, servletResponse);
        System.out.println();

    }


    private void add(String name, ServletResponse servletResponse) throws IOException {
        RoleBean roleBean=new RoleBean();
        roleBean.setName(name);
        Integer integer = roleService.addRole(roleBean);
        printData(integer>0,null,500, servletResponse);
        System.out.println();
    }
}
